package game;



import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;

import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.KeyListener;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.state.BasicGameState;
import org.newdawn.slick.state.StateBasedGame;

import paintball.PaintballPlayer;
import vision.Vision;
import controllers.PlayerController;

public class TwistyBasicGameState extends BasicGameState implements KeyListener {

	//The vision part
	protected Vision vision;
	//The map of the game
	protected GameMap map = new GameMap(Constants.screenWidth, Constants.screenHeight);

	//Whether the game needs to transit to the menu
	protected boolean goToMenu = false;
	//Cheatcodes
	String cheatCodes = "";
	//The IPAddress
	String IPAddress = "";
	
	public TwistyBasicGameState(Vision vision){
		this.vision = vision;
		setIPAddress();
	}
	
	@Override
	public void init(GameContainer container, StateBasedGame game)
			throws SlickException {
		
	}

	@Override
	public void render(GameContainer container, StateBasedGame game, Graphics g)
			throws SlickException {
		g.drawString(IPAddress, 0, Constants.screenHeight - 20);
	}

	@Override
	public void update(GameContainer container, StateBasedGame game, int delta)
			throws SlickException {
		int[][] map = vision.getMap();
		try{
			ArrayList<PaintballPlayer> players = PlayerController.getPlayers();
			for(PaintballPlayer p : players){
				if(p.getY() > 0 && p.getX() > 0){
					if(map[p.getY()][p.getY()] ==  1) { //@todo 
						map[p.getY()][p.getX()] = 0;
					}
				}
			}
		}catch(Exception e){
			
		}
		this.map.setMap(map);
		//this.map.setMap(this.finder.get_field());
		
		try{
			for(PaintballPlayer p : PlayerController.getPlayers()){
				if(!p.getReceived()){
					p.pingPong();
				}else{
					p.checkReceived();
				}
			}
			
			if(PlayerController.getPlayers().size() == 0 && game.getCurrentStateID() == 1){
				goToMenu = true;
			}
		}catch(Exception e){
			
		}
		
		if(goToMenu){
			goToMenu = false;
			goToMenu_event();
			game.enterState(0);
		}
	}
	
	/**
	 * The event that's called when the state changed to the menu.
	 * Can be overridden by subclasses
	 */
	protected void goToMenu_event(){
		
	}
	
	/**
	 * Sets the IPAddress
	 */
	public void setIPAddress(){
		try {
			InetAddress addr = InetAddress.getLocalHost();
			IPAddress = addr.getHostAddress();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public int getID() {
		// TODO Auto-generated method stub
		return -1;
	}
	
	@Override
	public void keyPressed(int key, char c) {
		if (key == Input.KEY_V) {
			goToMenu = true;
		}
		if( key == Input.KEY_Q) {
			System.exit(0);
		}
	}

}
